package cn.com.woxitech.dev.controller;


import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;

import cn.com.woxitech.dev.common.APIResultFactory;
import cn.com.woxitech.dev.common.Const;
import cn.com.woxitech.dev.common.EncryptionUtils;
import cn.com.woxitech.dev.common.JSONUtils;
import cn.com.woxitech.dev.common.SMSCodeUtils;
import cn.com.woxitech.dev.model.WmFronUser;
import cn.com.woxitech.dev.model.gen.WmApp;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.AppService;
import cn.com.woxitech.dev.service.CatalogService;
import cn.com.woxitech.dev.service.OrganizationPrivilegeService;
import cn.com.woxitech.dev.service.OrganizationService;
import cn.com.woxitech.dev.service.SMSCodeService;
import cn.com.woxitech.dev.service.UserService;
import cn.com.woxitech.dev.service.WeixinService;

@RestController
@RequestMapping(value="/wjt")
public class RegisterController{
	private static final Logger logger = Logger.getLogger(RegisterController.class);
	@Autowired 
	private UserService userService;
	@Autowired
	private OrganizationService organizationService;
	@Autowired
	private OrganizationPrivilegeService organizationPrivilegeService;
	@Autowired
	private SMSCodeService smsCodeService;
	@Autowired
	private WeixinService weixinService;
	@Autowired
	private CatalogService catalogService;
	@Autowired
	private AppService appService;
	
	@RequestMapping(value="/app/user_login_update",method=RequestMethod.POST)
	public Object app_user_login_update(@RequestBody String body){
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			String unionid = jsonNode.get("unionid").asText();
			
			String name = "";
			
			String systemType = jsonNode.get("systemType").asText();
			if(systemType.equals("ios")){
				
				name = new String(jsonNode.get("name").asText().getBytes("ISO-8859-1"),"utf-8");
			}else{
				name = jsonNode.get("name").asText();				
			}
			
			
			String headimgurl = jsonNode.get("headimgurl").asText();
			String tel = jsonNode.get("tel").asText();
			Date lastlogin = new Date(System.currentTimeMillis());
			
			WmUser user = userService.getUserByUnionId(unionid);
			
			if(user != null){
				
				user.setName(name);
				user.setWxHeadimgurl(headimgurl);
				user.setLastlogin(lastlogin);
				user.setTel(tel);
				
				userService.updateUser(user);
				
			}else{
				
				user = new WmUser();
				user.setCreatetime(new Date(System.currentTimeMillis()));
				user.setLastlogin(new Date(System.currentTimeMillis()));
				user.setName(name);
				user.setTel(tel);
				user.setWxUnionid(unionid);
				user.setWxHeadimgurl(headimgurl);
				user.setUuid(UUID.randomUUID().toString());
				
			}
			
			
			
			return APIResultFactory.success();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		} 
		
	}
	@RequestMapping(value="/app/login_init",method=RequestMethod.POST)
	public Object app_login_init(HttpServletResponse response,@RequestBody String body) throws JsonProcessingException, IOException {
		logger.info("app_login_init");
		try {
			Map<String, Object> mp = new HashMap<String, Object>();
			
			JsonNode jsonNode = JSONUtils.toJson(body);
			String wxunionid = jsonNode.get("unionid").asText();
			String accesstoken = jsonNode.get("accesstoken").asText();
			String openid = jsonNode.get("openid").asText();
			
			String systemType = jsonNode.get("systemType").asText();
			String nickname = "";
			if(systemType.equals("ios")){
				
				nickname = new String(jsonNode.get("nickname").asText().getBytes("ISO-8859-1"),"utf-8");
			}else{
				nickname = jsonNode.get("nickname").asText();				
			}

			int appid = 1;
			if(jsonNode.get("appid") != null){
				try{
					appid = jsonNode.get("appid").asInt();
				}catch(Exception e){
					appid = 1;
				}
			}
			WmApp wmApp = appService.getWmAppById(appid);
			String orgUuid = wmApp.getDefaultorguuid();
			String default_catalogUuid = wmApp.getDefaultcataloguuid();
			
			
			String headimgurl = jsonNode.get("headimgurl").asText();
		
			WmUser user = userService.getUserByUnionId(wxunionid);
			
			if(user == null){
				user = new WmUser();
				user.setCreatetime(new Date(System.currentTimeMillis()));
				user.setOpenOpenid(openid);
				user.setOpenAccessToken(accesstoken);
				user.setWxNickname(nickname);
				user.setName(nickname);
				user.setWxHeadimgurl(headimgurl);
				user.setWxUnionid(wxunionid);
				user.setUuid(UUID.randomUUID().toString());
				user.setLastlogin(new Date(System.currentTimeMillis()));
				this.userService.insertUser(user);
				
				mp.put("next", true);
				
			}else{
				
				if(user.getTel() == null || user.getTel().trim().length() == 0){
					
					
					mp.put("next", true);
					
				}else{
					
					mp.put("next", false);	
				}
				
			}
			
			//第一版，所有用户默认添加上科大的专题
			this.catalogService.insertCatalog_User(default_catalogUuid, user.getUuid());
			
			mp.put("headimgurl", user.getWxHeadimgurl());
			mp.put("name", user.getName());
			mp.put("unionid", user.getWxUnionid());
			
			
			return APIResultFactory.success(mp);
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();	
		}
	}
	
	@RequestMapping(value="/login_init",method=RequestMethod.POST)
	public Object login_init(HttpServletResponse response,@RequestBody String body) throws JsonProcessingException, IOException {
		logger.info("login_init");
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			String wxunionid = jsonNode.get("unionid").asText();
			WmUser user = userService.getUserByUnionId(wxunionid);
			
			if(user == null){
				return APIResultFactory.fail();
			}
			Map<String, Object> mp = new HashMap<String, Object>();
			
			WmFronUser fronUser = new WmFronUser();
			fronUser.setHeadImageUrl(user.getWxHeadimgurl());
			fronUser.setName(user.getName());
			fronUser.setTel(user.getTel());
			fronUser.setUnionid(user.getWxUnionid());
			fronUser.setUuid(user.getUuid());
			
			mp.put("frontUser", fronUser);
			
			String access_token = user.getuAccessToken();
			String refresh_token = user.getuRefreshToken(); 
			String openid = user.getWxOpenid();
			WmUser u = this.weixinService.getUserInfoFromWeiXin(access_token, refresh_token, openid);
			mp.put("weixinavatarUrl", u.getWxHeadimgurl());
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();	
		}
	}
	@RequestMapping(value="/baseinfo_update", method=RequestMethod.POST)
	public Object baseinfo_update(@RequestBody String body) throws JsonProcessingException, IOException{
		logger.info("baseinfo_update");
		JsonNode jsonNode = JSONUtils.toJson(body);
		
		String systemType = jsonNode.get("systemType").asText();

		
		WmUser user = new WmUser();
		String unionid = null;
		if(jsonNode.get("unionid") != null){
			unionid = jsonNode.get("unionid").asText();
		}
		String uuid = null;
		if(jsonNode.get("uuid") != null){
			uuid = jsonNode.get("uuid").asText();
		}
		String tel = null;
		if(jsonNode.get("tel") != null){
			tel = jsonNode.get("tel").asText();
			user.setTel(tel);
		};
		String name = null;
		if(jsonNode.get("name") != null){
			
			if(systemType.equals("ios")){
				name = new String(jsonNode.get("name").asText().getBytes("ISO-8859-1"),"utf-8");
			}else{
				name = jsonNode.get("name").asText();	
			}
			
			user.setName(name);
		};
		
		if(name != null || tel != null){

			if(unionid != null){
				userService.updateUserByUnionid(user, unionid);
			}else if(uuid != null){
				userService.updateUserByUuid(user, uuid);	
			}else{
				return APIResultFactory.fail();
			}
		}else{
			return APIResultFactory.fail();
		}
		
		
		return APIResultFactory.success();
	}
	
	
	
	@RequestMapping(value="/login_code_validate", method=RequestMethod.POST)
	public Object validateCodeLogin(@RequestBody String body) throws JsonProcessingException, IOException{
		
		JsonNode jsonNode = JSONUtils.toJson(body);
		String phoneNum = jsonNode.get("phoneNum").asText();
		String code = jsonNode.get("code").asText();
		String name = jsonNode.get("name").asText();
		String headImageUrl = jsonNode.get("headImageUrl").asText();
		String userUuid = jsonNode.get("userUuid").asText();
		
		boolean isTrue = smsCodeService.validateSMSVerifyCode(phoneNum, code);
		if (isTrue) {
			
			WmUser user = userService.getUserByUuid(userUuid);
			user.setTel(phoneNum);
			user.setName(name);
			user.setWxHeadimgurl(headImageUrl);
			userService.updateUser(user);
						
			return APIResultFactory.success();
		}else {
			return APIResultFactory.fail();
		}
	}
	
	@RequestMapping(value="/login/encryvalid", method=RequestMethod.POST)
	public Object wjt_login_encryvalid(@RequestBody String body) {
		
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
		
			String val_encry = jsonNode.get("encry").asText();

			//?unionid=o9SI3t5zIxt0rkk9_4w8AshIJcWI&time=1470196134820
			String val = EncryptionUtils.decode(val_encry);

			long now = System.currentTimeMillis();
			
			int len1 = "?unionid=".length();
			int len2 = "&time=".length();
			int len = val.length();
			int p1 = val.indexOf("&time=");
			
			
			String id = val.substring(len1, p1);
			long time = Long.parseLong(val.substring(p1 + len2));
			
//			if((now - time)/1000 > 3600){
//				return APIResultFactory.fail("认证已超时请重新登录");
//			} 
			
			WmUser user = this.userService.getUserByUnionId(id);
			if(user == null){
				return APIResultFactory.fail("用户权限认证不正确请重新登录");
			}
			
			return APIResultFactory.success(id);
		
		
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return APIResultFactory.fail("用户权限认证不正确请重新登录");
	}
}
